<template>
  <div>
    <a-input placeholder="请选择枚举" readonly :value="dictName" @click="openModal"/>
    <HModal @mousedown.native.stop :width="800" :height="700"
            :visible="visible" @ok="handleOK" @cancel="close">
      <template #title>
        <a-tabs v-model="active">
          <a-tab-pane tab="公共枚举" key="system"/>
          <a-tab-pane tab="应用枚举" key="app"/>
          <a-tab-pane tab="基本档案" key="baseData"/>
        </a-tabs>
      </template>
      <SystemDictSelector v-show="active === 'system'" ref="system" v-model="tempFieldConfig"/>
    </HModal>
  </div>
</template>
<script>
import HModal from '@comp/hhd/HModal/HModal.vue';
import {createProps} from '@/utils';
import {createField} from '@comp/hhd/design/FormDesigner/types';
import SystemDictSelector from '@comp/hhd/design/FormDesigner/DictBinder/SystemDictSelector.vue';
import {getAction} from '@api/manage';

export default {
  name: 'DictBinder',
  model: createProps('fieldConfig'),
  props: {
    fieldConfig: createProps(Object, createField)
  },
  components: {
    SystemDictSelector,
    HModal
  },
  data() {
    return {
      tempFieldConfig: {
        dict: undefined,
        dictType: undefined
      },
      visible: false,
      active: undefined,
      dictName: undefined
    };
  },
  methods: {
    handleOK() {
      let ref = this.$refs[this.active];
      let data = ref.getData && ref.getData() || undefined;
      if (!data) {
        this.$message.warn('请选择字典');
        return;
      }
      this.fieldConfig.dict = data.dict;
      this.fieldConfig.dictType = data.dictType;
      this.close();
    },
    openModal() {
      this.open();
      this.tempFieldConfig.dict = this.fieldConfig.dict;
      this.tempFieldConfig.dictType = this.fieldConfig.dictType;
      this.active = this.tempFieldConfig.dictType || 'system';
    },
    open() {
      this.visible = true;
    },
    close() {
      this.visible = false;
    },
    loadDictItems() {
      this.fieldConfig.dict
      && this.fieldConfig.dictType
      && getAction('/form/loadDictItems', {
        dictCode: this.fieldConfig.dict,
        dictType: this.fieldConfig.dictType
      })
      .then(({result}) => {
        this.dictName = result.dictName;
      });
    },
  },
  watch: {
    'fieldConfig.dict': {
      handler() {
        this.loadDictItems();
      },
      immediate: true,
    },
    active: {
      handler() {
        this.$nextTick(() => {
          this.$refs[this.active] && this.$refs[this.active].init && this.$refs[this.active].init();
        });
      },
      immediate: true,
    }
  }
};
</script>